package com.zhs.base.loadbalance;

import com.zhs.base.service.MapApiService;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 平滑权重轮询
 * @author Java架构师之旅
 * @date 2022年08月15日 17:09.
 */
@Slf4j
public class SmoothWeightPolling {
    private static final Map<MapApiService, Weight> weightMap = new HashMap<>();
    public static MapApiService getMapApiService(Map<MapApiService, Integer> weightList){
        int totalWeight = 0;

        // 计算总的权重
        totalWeight = weightList.values().stream().reduce(0, Integer::sum);
        if (weightMap.isEmpty()){
            weightList.forEach((key,value)->{
                weightMap.put(key,new Weight(key,value,value));
            });
        }
        // 选择当前权重最大的数据
        Weight maxCurrentWeight = null;
        for (Weight weight : weightMap.values()) {
            if (null ==maxCurrentWeight || weight.getCurrentWeight()>maxCurrentWeight.getCurrentWeight()){
                maxCurrentWeight = weight;
            }
        }
        // 将maxCurrentWeight减去总权重和
        maxCurrentWeight.setCurrentWeight(maxCurrentWeight.getCurrentWeight() -totalWeight);

        // 所有ip的currentWeight全部加上元素权重
        for (Weight weight : weightMap.values()) {
            weight.setCurrentWeight(weight.getCurrentWeight()+weight.getWeight());
        }
        // 返回maxCurrentWeight所对应ip
        return maxCurrentWeight.getMapApiService();
    }
}
